<?php

namespace app\api\controller;


use app\mqtt\controller\Mqtt;

/**
 * 功能说明: 设备管理类
 * Company:物联网应用专家---成都亿佰特电子科技有限公司
 * User: 郑文军
 * Time: 2021-09-30 14:50
 * version：1.0
 */
class Device extends Base
{
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 功能说明 获取当前登录账号分组列表
     * author 郑
     * time 2021-04-19 17:20
     */
    public function index()
    {
        $search = request()->param();
        $search['str'] = isset($search['str']) ? $search['str'] : "";

        $where = "name like '%{$search['str']}%' or remarks like '%{$search['str']}%'";

        $res = db('project')
            ->field("id,name,from_unixtime(create_time) create_time,sort,remarks")
            ->order("sort desc,id desc")
            ->where($where)
            ->where(['delete' => 0, 'uid' => $this->accessData['uid']])
            ->paginate($search['pageSize'], false, ['page' => $search['page']]);
        suc($res);
    }


    public function getTop()
    {
        $param = request()->only(['id']);
        $where = [];
        if (isset($param['id']) && $param['id']) {
            $where['pid'] = $param['id'];
        }
        $uid = $this->accessData['uid'];
        //设备总数
        $res['count'] = db("device")->where($where)->where(['uid' => $uid, 'delete' => 0])->count();
        //在线总数
        $res['online'] = db("device")->where($where)->where(['uid' => $uid, 'delete' => 0, 'start' => ['neq', 0]])->count();
        //离线总数
        $res['notline'] = db("device")->where($where)->where(['uid' => $uid, 'delete' => 0, 'start' => 0])->count();
        //在线百分比
        $res['onlinePercentage'] = $res['count'] == 0 ? 0 : intval($res['online'] / $res['count'] * 100);
        suc($res);
    }

    /**
     * 功能说明 获取全部分组信息
     * author 郑
     * time 2021-09-30 15:54
     */
    public function getAll()
    {
        $res = db('project')
            ->field("id value,name label")
            ->order("sort desc,id desc")
            ->where(['delete' => 0, 'uid' => $this->accessData['uid']])
            ->select();
        suc($res);
    }

    /**
     * 功能说明 获取所有设备
     * author 郑
     * time 2021-09-30 15:54
     */
    public function getAllDevice()
    {
        $res = db('device')
            ->field("id,name,code")
            ->order("id desc")
            ->where(['delete' => 0, 'uid' => $this->accessData['uid']])
            ->select();
        suc($res);
    }

    /**
     * 功能说明 设备列表
     * author 郑
     * time 2021-09-30 15:56
     */
    public function content()
    {
        $search = request()->param();
        $search['str'] = isset($search['str']) ? $search['str'] : "";
        $whereLike = "c.name like '%{$search['str']}%' or c.remarks like '%{$search['str']}%' and c.code like '%{$search['str']}%'";
        $where = ['delete' => 0, 'uid' => $this->accessData['uid']];
        if (isset($search['pid']) && $search['pid']) {
            $where['pid'] = $search['pid'];
        }
        $res = db('device c')
            ->field("c.*")
            ->order("id desc")
            ->where($where)
            ->where($whereLike)
            ->paginate($search['pageSize'], false, ['page' => $search['page']]);
        foreach ($res as $k => $v) {
            //获取设备类型
            $type = db("type t")->field('t.name tname,t.model')->where(['t.id' => $v['typeId']])->find();
            $v['create_time'] = date("Y-m-d", $v['create_time']);
            $v['tname'] = $type['tname'];
            $v['model'] = $type['model'];
            //获取设备分组
            $equipment = db("device")->field('name')->where(['id' => $v['pid']])->find();
            $v['equipment'] = $equipment['name'];
            $res[$k] = $v;
        }
        suc($res);
    }

    /**
     * 功能说明 添加分组
     * author 郑
     * time 2021-09-30 16:03
     */
    public function addSubmit()
    {
        $param = request()->param();
        $param['create_time'] = time();
        $param['uid'] = $this->accessData['uid'];
        $res = db("project")->insert($param);
        $res ? suc("", "操作成功") : err("", "操作失败");
    }

    /**
     * 功能说明 修改分组
     * author 郑
     * time 2021-09-30 16:15
     */
    public function updateSubmit()
    {
        $param = request()->param();
        unset($param['$index']);
        unset($param['create_time']);
        $res = db("project")->where(['id' => $param['id']])->update($param);
        $res ? suc("", "操作成功") : err("", "操作失败");
    }

    /**
     * 功能说明 删除分组
     * author 郑
     * time 2021-09-30 16:19
     */
    public function del()
    {
        $param = request()->param();
        $res = db("project")->where(['id' => $param['id']])->delete();
        db("device")->where(['pid' => $param['id']])->delete();
        $res ? suc("", "操作成功") : err("", "操作失败");
    }


    /**
     * @author 郑
     * @DataTime: 2020/8/4 10:40
     * @功能说明:添加设备 操作
     */
    public function deviceAdd()
    {
        $param = request()->only(['code', 'remarks', 'name', 'pid']);

        $param['create_time'] = time();
        $param['uid'] = $this->accessData['uid'];

        //获取设备类型
        $typeCode = substr($param['code'], 0, 3);
        //写死设备类型
        $type = db("type")->where(['code' => '111'])->find();
        if (!$type) {
            err("", "该设备类型不存在");
        } else {
            $param['typeId'] = $type['id'];
        }
        $isRun = db('device')->where(['code' => $param['code'], 'delete' => 0])->find();
        if ($isRun && $isRun['uid'] == $this->accessData['uid']) {
            err("", "您已录入该设备");
        } else if ($isRun && $isRun['uid'] != $this->accessData['uid']) {
            err("", "设备已被他人绑定");
        }

        $res = db("device")->insert($param);
        $res ? suc("", "操作成功") : err("", "操作失败");
    }

    /**
     * 功能说明 更新设备
     * author 郑
     * time 2021-09-30 17:29
     */
    public function deviceUpdate()
    {
        $param = request()->only(['id', 'name', 'remarks', 'pid']);
        unset($param['$index']);
        $res = db("device")->where(['id' => intval($param['id'])])->update($param);
        $res ? suc("", "操作成功") : err("", "操作失败");
    }

    /**
     * 功能说明 删除设备
     * author 郑
     * time 2021-09-30 17:33
     */
    public function deviceDel()
    {
        $param = request()->param();
        $res = db("device")->where(['id' => $param['id']])->delete();
        $res ? suc("", "操作成功") : err("", "操作失败");
    }

    /**
     * 功能说明 配置设备信息
     * author 郑
     * time 2021-10-11 15:19
     */
    public function configSubmit()
    {
        $param = request()->param();
        $res = db("device")
            ->where(['id' => ['in', $param['id']]])
            ->update(['keepAliveTime' => $param['keepAliveTime'], 'keepAliveDate' => $param['keepAliveDate']]);

        $res = db("device")->field("id,code")->where(['id' => ['in', $param['id']]])->select();
        //发送socket消息
        $mqtt = new Mqtt();
        foreach ($res as $v) {
            $message = [];
            $message['msgId'] = date("YmdHis") . rand(100000, 999999);
            $message['sn'] = $v['code'];
            $message['method'] = 'cfgSysParams';
            $message['params']['keepAliveTime'] = $param['keepAliveTime'];
            $message['params']['data'] = $param['keepAliveDate'];
            $mqtt->SendMessage("all/" . $v['code'] . '/sub', json_encode($message));
        }
        $res ? suc("", "操作成功") : err("", "操作失败");
    }

    /**
     * 功能说明 获取单台设备详情
     * author 郑
     * time 2021-10-11 17:23
     */
    public function getDevice()
    {
        $param = request()->param();
        $res = db("device")->where(['id' => $param['id']])->find();
        $res['last_login_time'] = date("Y-m-d H:i:s", $res['last_login_time']);
        //统计AI，DI,DO,PWM总量
        $res['ai'] = db("device_ai")->where(['did' => $res['id']])->count();
        $res['di'] = db("device_di")->where(['did' => $res['id']])->count();
        $res['do'] = db("device_do")->where(['did' => $res['id']])->count();
        $res['pwm'] = db("device_pwm")->where(['did' => $res['id']])->count();
        suc($res);
    }

    /**
     * 功能说明 获取单台设备AI，DI，DO,PWM参数
     * author 郑
     * time 2021-10-12 9:41
     */
    public function getDeviceDetail()
    {
        $param = request()->param();
        $date = [];
        $date['AI'] = db("device_ai")->where(['did' => $param['id']])->select();
        $date['DI'] = db("device_di")->where(['did' => $param['id']])->select();
        $date['DO'] = db("device_do")->where(['did' => $param['id']])->select();
        $date['PWM'] = db("device_pwm")->where(['did' => $param['id']])->select();
        $date['UART'] = db("device_uart")->where(['did' => $param['id']])->select();
        $date['detail'] = db("device")->where(['id' => $param['id']])->find();
        suc($date);
    }

    /**
     * 功能说明 更新AI数据
     * author 郑
     * time 2021-10-12 13:39
     */
    public function DIUpdate()
    {
        $param = request()->param();
        //发布MQTT消息到设备
        $device = db("device")->where(['id' => $param['did']])->find();
        $message['msgId'] = date("YmdHis") . rand(100000, 999999);
        $message['sn'] = $device['code'];
        $message['method'] = "cfgDIParams";
        $message['params'] = ['num' => $param['num'], 'isPost' => $param['isPost']];
        $mqtt = new Mqtt();
        $mqtt->SendMessage('all/' . $device['code'] . '/sub', json_encode($message));
        suc("", "更新成功");
    }

    public function DOUpdate()
    {
        $param = request()->param();
        //发布MQTT消息到设备
        $device = db("device")->where(['id' => $param['did']])->find();
        $message['msgId'] = date("YmdHis") . rand(100000, 999999);
        $message['sn'] = $device['code'];
        $message['method'] = "cfgDOParams";
        $message['params'] = ['num' => $param['num'], 'isPost' => $param['isPost'], 'pulseTime' => $param['pulseTime']];
        $mqtt = new Mqtt();
        $mqtt->SendMessage('all/' . $device['code'] . '/sub', json_encode($message));
        suc("", "更新成功");
    }

    /**
     * 功能说明 AI更新
     * author 郑
     * time 2021-10-12 15:56
     */
    public function AIUpdate()
    {
        $param = request()->param();
        //发布MQTT消息到设备
        $device = db("device")->where(['id' => $param['did']])->find();
        $message['msgId'] = date("YmdHis") . rand(100000, 999999);
        $message['sn'] = $device['code'];
        $message['method'] = "cfgAIParams";
        $message['params'] = ['num' => $param['num'], 'isPost' => $param['isPost']];
        $mqtt = new Mqtt();
        $mqtt->SendMessage('all/' . $device['code'] . '/sub', json_encode($message));
        suc("", "更新成功");
    }

    /**
     * 功能说明 PWM配置更新
     * author 郑
     * time 2021-10-12 16:21
     */
    public function PWMUpdate()
    {
        $param = request()->param();
        //发布MQTT消息到设备
        $device = db("device")->where(['id' => $param['did']])->find();
        $message['msgId'] = date("YmdHis") . rand(100000, 999999);
        $message['sn'] = $device['code'];
        $message['method'] = "cfgPWMParams";
        $message['params'] = ['num' => $param['num'], 'highLevelCnt' => $param['highLevelCnt'],
            'frqDiv' => $param['frqDiv'], 'totalCnt' => $param['totalCnt']];
        $mqtt = new Mqtt();
        $mqtt->SendMessage('all/' . $device['code'] . '/sub', json_encode($message));
        suc("", "更新成功");
    }

    /**
     * 功能说明 UART配置更新
     * author 郑
     * time 2021-10-12 16:21
     */
    public function UARTUpdate()
    {
        $param = request()->param();
        //发布MQTT消息到设备
        $device = db("device")->where(['id' => $param['did']])->find();
        $message['msgId'] = date("YmdHis") . rand(100000, 999999);
        $message['sn'] = $device['code'];
        $message['method'] = "cfgPWMParams";
        $message['params'] = ['num' => $param['num'], 'baud' => intval($param['baud']),
            'parity' => $param['parity'], 'dataBits' => intval($param['dataBits']), 'stop' => intval($param['stop'])];
        $mqtt = new Mqtt();
        $mqtt->SendMessage('all/' . $device['code'] . '/sub', json_encode($message));
        suc("", "更新成功");
    }

    /**
     * 功能说明 设置DO状态
     * author 郑
     * time 2021-10-13 9:49
     */
    public function DOSetting()
    {
        $param = request()->param();
        $device = db("device")->where(['id' => $param['did'], 'uid' => $this->accessData['uid']])->find();
        if (!$device) {
            err("为查找到设备信息", "");
        }

        //转发控制指令
        $message['msgId'] = date("YmdHis") . rand(100000, 999999);
        $message['sn'] = $device['code'];
        $message['method'] = "setDOStatus";
        $message['params'] =[['num' => $param['num'], 'value' => $param['value'] == true ? 1 : 0]];
        $mqtt = new Mqtt();
        $mqtt->SendMessage('all/' . $device['code'] . '/sub', json_encode($message));
        suc("", "操作成功");
    }


    /**
     * 功能说明 设置PWM状态
     * author 郑
     * time 2021-10-13 10:24
     */
    public function PWMSetting()
    {
        $param = request()->param();
        $device = db("device")->where(['id' => $param['did'], 'uid' => $this->accessData['uid']])->find();
        if (!$device) {
            err("为查找到设备信息", "");
        }

        //转发控制指令
        $message['msgId'] = date("YmdHis") . rand(100000, 999999);
        $message['sn'] = $device['code'];
        $message['method'] = "setPWMStatus";
        $message['params'] = ['num' => $param['num'], 'status' => $param['value'] == true ? 1 : 0];
        $mqtt = new Mqtt();
        $mqtt->SendMessage('all/' . $device['code'] . '/sub', json_encode($message));
        suc("", "操作成功");
    }

    /**
     * 功能说明 设备重启
     * author 郑
     * time 2021-10-20 10:38
     */
    public function reboot()
    {
        $param = request()->param();
        foreach ($param['id'] as $v) {
            $device = db("device")->where(['id' => $v, 'uid' => $this->accessData['uid']])->find();
            if ($device) {
                //转发重启指令
                $message['msgId'] = date("YmdHis") . rand(100000, 999999);
                $message['sn'] = $device['code'];
                $message['method'] = "reboot";
                $mqtt = new Mqtt();
                $mqtt->SendMessage('all/' . $device['code'] . '/sub', json_encode($message));

            }
        }
        suc("", "操作成功");
    }

    /**
     * 功能说明 设备恢复出厂
     * author 郑
     * time 2021-10-20 10:38
     */
    public function reload()
    {
        $param = request()->param();
        foreach ($param['id'] as $v) {
            $device = db("device")->where(['id' => $v, 'uid' => $this->accessData['uid']])->find();
            if ($device) {
                //转发重启指令
                $message['msgId'] = date("YmdHis") . rand(100000, 999999);
                $message['sn'] = $device['code'];
                $message['method'] = "reload";
                $mqtt = new Mqtt();
                $mqtt->SendMessage('all/' . $device['code'] . '/sub', json_encode($message));

            }
        }
        suc("", "操作成功");
    }

    /**
     * 功能说明 发送Uart数据
     * author 郑
     * time 2021-10-20 10:38
     */
    public function sendUARTData()
    {
        $param = request()->param();
        $device = db("device")->where(['id' => $param['id'], 'uid' => $this->accessData['uid']])->find();
        if ($device) {
            //转发重启指令
            $message['msgId'] = date("YmdHis") . rand(100000, 999999);
            $message['sn'] = $device['code'];
            $message['method'] = "sendUARTData";
            $message['params']=['num'=>$param['num'],'message'=>$param['text']];
            $mqtt = new Mqtt();
            $mqtt->SendMessage('all/' . $device['code'] . '/sub', json_encode($message));
            suc("", "操作成功");
        }
        err("","操作失败");
    }
}